﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConnectionControl;
using ProtHandlers;

namespace pokerServer.ProtHandlers
{
	//Command Pattern
	class ProtHandler : IProtHandle
	{
		HandlerFact hf;
		String[] command;
		ClientConnection cc;
		ConnectionManag cm;
		Boolean setForClose = false;
		public ProtHandler(ClientConnection cc , ConnectionManag cm)
		{
			hf = new HandlerFact();
			this.cc = cc;
			this.cm = cm;
		}

		public void assignCommand(String[] command)
		{
			this.command = command;
		}


		public String work()
		{
			if (command[0].Contains("AUTH") && this.cc.isLoggedin)
			{
				this.setForClose = true;
				return "AUTH-FAIL ConnectionAlreadyOpen!";
			}
			if (command[0].Contains("AUTH") && this.cm.exists(command[1]))
			{
				this.setForClose = true;
				return "AUTH-FAIL UserAlreadyLogged!";
			}
			IProtHandle handler = hf.getHandler(command,this.cm,this.cc);			
			String s = handler.work();
			analyzeWork(s);
			return s;
			
		}

		private void analyzeWork(String workres)
		{
			switch (hf.getState())
			{
				case States.AUTH:
					authState(workres);
					break;
				case States.REGISTER:
					regState(workres);
					break;
				case States.JOINTABLE:
				case States.PARTTABLE:
				case States.SEATDOWNTABLE:
				case States.SEATUPTABLE:
				case States.ACTION:
					break;
				case States.REQUEST:
					break;
				default:
					quitState(workres);
					break;
			}
			
		}

		private void authState(String workres)
		{
			if (workres.Contains("AUTH-FAIL"))
			{
				this.cm.removeTemp(this.cc);
				this.setForClose = true;
			}
			else
			{
				if (!this.cc.isLoggedin)
				{
					this.cm.addPerm((cc.conName = this.command[0]), this.cc);
					this.cc.isLoggedin = true;
				}

			}

		}
		private void regState(String workres)
		{
			this.setForClose = true;
		}
		private void quitState(String workres)
		{
			workres += this.cc.conName;
			this.setForClose = true;
		}
		public Boolean toClose()
		{
			return setForClose;
		}

	}
}
